#include <iostream>
#include <vector>
#include <cstdio>
#include <cstring>
#include <unordered_map>
#include <ctime>
#include <cstdlib>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <cassert>
using namespace std;
//演示pipe通信的基本过程 -- 匿名管道
int main()
{
    // 1. 创建管道
    int pipefd[2] = {0};
    if(pipe(pipefd) != 0)
    {
        cerr << "pipe error" << endl;
        return 1;
    }
    // 2. 创建子进程
    pid_t id = fork();
    if(id < 0)
    {
        cerr << "fork error" << endl;
        return 2;
    }
    else if (id == 0)
    {
        // child
        // 子进程来进行读取, 子进程就应该关掉写端
        close(pipefd[1]);
        #define NUM 1024
        char buffer[NUM];
        while(true)
        {
            cout<<"进入了子进程"<<endl;
            cout << "时间戳: " << (uint64_t)time(nullptr) << endl;
            // 子进程没有带sleep，为什么子进程你也会休眠呢？？
            memset(buffer, 0, sizeof(buffer));
            //sleep(100);
            ssize_t s = read(pipefd[0], buffer, sizeof(buffer) - 1);
            if(s > 0)
            {
                //读取成功
                buffer[s] = '\0';
                cout << "子进程收到消息,内容是: " << buffer << endl;
            }
            else if(s == 0)
            {
                cout << "父进程写完了，我也退出啦" << endl;
                break;
            }
            else{
                //Do Nothing
            }
        }
        close(pipefd[0]);
        exit(0);
    }
    else
    {
        // parent
        // 父进程来进行写入，就应该关掉读端
        close(pipefd[0]);
        const char *msg = "你好子进程，我是父进程, 这次发送的信息编号是: ";
        int cnt = 0;
        // while(cnt < 5)
        while(cnt<5)
        {
            char sendBuffer[1024];
            sprintf(sendBuffer, "%s : %d", msg, cnt);
            //sleep(30); // 这里是为了一会看现象明显
            sleep(1);
            write(pipefd[1], sendBuffer, strlen(sendBuffer)); //要不要+1 1,0
            cnt++;
            cout << "cnt: " << cnt << endl;
        }
        close(pipefd[1]);
        cout << "父进程写完了" << endl;
    }
    pid_t res = waitpid(id, nullptr, 0);
    if(res > 0)
    {
        cout << "等待子进程成功" << endl;
    }
    // 0 -> 嘴巴 -> 读（读书）
    // 1 -> 笔 -> 写的
    // cout << "fd[0]: " << pipefd[0] << endl;
    // cout << "fd[1]: " << pipefd[1] << endl;
    return 0;
}